package com.chatplus.application.aiprocessor.platform.chat.baidu;

import cn.bugstack.openai.executor.model.baidu.config.BaiduConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.interceptor.DynamicKeyHandleInterceptor;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.aiprocessor.util.WebSocketManager;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;


/**
 * 百度 文心一言 机器人处理器
 **/
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "BaiDu")
public class BaiDuProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(BaiDuProcessor.class);

    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            openAiSession.completions(request, new CommonEventSourceListener(chatRequest));
        }
    }

    @Override
    public String processSync() {
        return null;
    }

    @Override
    public AiPlatformEnum getPlatform() {
        return AiPlatformEnum.BAI_DU;
    }

    @Override
    public synchronized OpenAiSession getSessionFactory() {
        instance();
        // 单独设置链接
        openApiKey.forEach(item -> {
            if (!item.getUrl().contains(BaiduConfig.CompletionsUrl.fromCode(chatRequest.getChatModel().getValue()).getUrl())) {
                item.setUrl(item.getUrl().concat(BaiduConfig.CompletionsUrl.fromCode(chatRequest.getChatModel().getValue()).getUrl()));
            }
        });
        // 2. 配置文件
        Configuration configuration = new Configuration();
        configuration.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        // 3. 会话工厂
        DefaultOpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
        factory.setInterceptor(new DynamicKeyHandleInterceptor(openApiKey, getPlatform()));
        OpenAiSession openAiSession = factory.openSession();
        WebSocketManager.addSeeClient(chatRequest.getSessionId(), openAiSession.getClient());
        return openAiSession;
    }
}
